package com.icesoft.core.web.controller;

import cn.hutool.core.io.IoUtil;
import com.icesoft.core.common.helper.Resp;
import com.icesoft.core.common.util.RegexUtils;
import com.icesoft.core.web.helper.PathUtil;
import com.icesoft.core.web.model.CryptoPublicKey;
import com.icesoft.core.web.suppose.safehttp.service.ICryptoKeyPairRepository;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;


/**
 * 公钥相关接口
 */
@RestController
@RequestMapping("public/crypto")
@AllArgsConstructor
public class PublicKeyController {
    private ICryptoKeyPairRepository cryptoKeyPairRepository;

    /**
     * 获取公钥接口
     */
    @GetMapping("publicKey")
    public Resp<CryptoPublicKey> publicKey() {
        return Resp.success(cryptoKeyPairRepository.findAllKey().stream().findAny().orElse(null));
    }

    /**
     * 获取公钥js接口
     */
    @GetMapping(value = "cryptoKey.js", produces = "application/javascript")
    public String rsaKey() throws IOException {
        InputStream inputStream = PathUtil.getPathInputStream("config/cryptoKey.js");
        String jsTemplate = IoUtil.readUtf8(inputStream);
        CryptoPublicKey cryptoPublicKey = cryptoKeyPairRepository.findAllKey().stream().findAny().orElse(null);
        if (cryptoPublicKey == null) {
            return "没有任何密钥";
        }
        Map<String, String> map = new HashMap<>();
        map.put("keyId", cryptoPublicKey.getKeyId());
        map.put("publicKey", cryptoPublicKey.getPublicKey());
        map.put("algorithm", cryptoPublicKey.getAlgorithm());
        return RegexUtils.processTemplate(jsTemplate, map);
    }

}
